import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Dimensions, Image, TouchableOpacity, FlatList
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import navigationSeevice from '../../../../../components/navigation/navigationSeevice';
import StorageHelper from '../../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../../config/storage';
import { Common } from '../../../../../component/common/Common';
import { RangTime } from '../../../../../component/common/RangTime';
import { CommonData } from './_common/common.js';
import moment from 'moment';
import { API, API_GENERATE } from '../../../../../config/api';
import HTTP from '../../../../../utils/http';
import { PageStatusIndex } from '../../../../../component/page-status/PageStatusIndex';
import Dictionary from '../../../../../utils/dictionary';

const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;
const scale = ScreenWidth / 375;

export class MaReComponent extends Component {
	static navigationOptions = {
		header: null
	}

	constructor(props) {
		super(props);
		this.state = {
			modalVisible: false,
			showTimeModal: false,
			checked: true,
			status: 'data',
			listData: [],
			refreshIcon: false, // 下拉刷新图标
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数
		this.headIndex = 0;
		this.department = null;
		this.headData = [
		];
		this.params = {
			beginDate: CommonData._format('date2', moment().subtract(1, 'months').calendar()),
			endDate: CommonData._format('date2', moment()),
			companyId: this.props.ortherData.companyInfoVO.companyId,
			onlyMe: true,
			visitType: '',
			pageNo: 1
		};
	}

	componentWillMount() {
		this._getUserId();
		this._init();
	}

	_getUserId = async () => {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		const userInfo = JSON.parse(userInfoJson);
		this.userId = userInfo.userId;
	}

	//初始函数
	_init = async () => {
		const { choice } = this.props;
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.params.pageNo == 1
		})
		this.params.corpId = choice.corpId;
		const res = await HTTP.POST(API_GENERATE(API.GET_STAFF_LIST), this.params);
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.params.pageNo == 1 ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
		let headList = await Dictionary.get('COMPANY_VISIT_TYPE');
		this.headData = []
		headList.map((item, index) => {
			this.headData.push({
				title: item.dictName,
				id: item.dictKey,
				page: index + 1
			})
		})
		this.headData.unshift({ title: "全部类型", id: "", page: 0 })
		console.log(this.headData)
	}

	reloadPage = () => {
		this.params.pageNo = 1;
		this.reload = true;
		this._init();
	}

	// 下拉刷新
	refresh = () => {
		this.params.pageNo = 1;
		this.reload = false;
		this._init();
	}

	// 上拉翻页
	loadMore = () => {
		if (this.totalPage > this.params.pageNo) {
			this.params.pageNo++;
			this.reload = false;
			this._init();
		}
	}

	//改变仅看自己状态
	changeCheck = () => {
		this.params.pageNo = 1;
		this.setState({
			checked: !this.state.checked
		}, () => {
			this.params.onlyMe = this.state.checked;
			this._init();
		})
	}

	//切换选项
	_itemFn = (sendObj) => {
		let sendPage = sendObj && sendObj.item ? sendObj.item.page || 0 : 0;
		this.headIndex = sendPage;
		this._showVisible();
		this.department = this.headData[sendPage]['title'];
		this.params.visitType = this.headData[sendPage]['id'];
		this.params.pageNo = 1;
		this.setState({
			modalVisible: !this.state.modalVisible
		}, () => {
			this._init();
		})
	}

	//打开类型选项
	_showVisible = () => {
		this.setState({
			modalVisible: !this.state.modalVisible
		})
	}

	//打开日历选项
	_timeOpen = () => {
		this.setState({
			showTimeModal: true
		})
	}

	// 选择时间
	_resultCall = (resultData) => {
		this.params.pageNo = 1;
		this.params.beginDate = resultData.startTime || '';
		this.params.endDate = resultData.endTime;
		this.setState({
			showTimeModal: false
		}, () => {
			this._init();
		})
	}

	_renderListItem = (data) => {
		let { contactorName, createTime, visitType, visitTypeName, organName, staffId, staffName, mobileNo, visitContent, detailAddress } = data.item;
		let mobile = mobileNo ? (this.userId == staffId ? mobileNo : `${mobileNo.substring(0, 3)}...${mobileNo.substring(8, 11)}`) : '--';
		data.item.mobileNo = mobile;
		let content = visitContent ? (visitContent.length > 50 ? (visitContent.substring(0, 50) + '...') : visitContent) : '无';
		return (
			<TouchableOpacity style={styles.cardBox} onPress={() => { navigationSeevice.navigate('MaintenanceDetails', data.item) }}>
				<View style={{ marginBottom: 5 * scale }}><Text style={{ color: '#34475F', fontSize: 10 * scale }}>{createTime && createTime.substring(0, 10)}</Text></View>
				<View style={styles.card}>
					<View style={styles.cardTop}>
						<View><Text style={{ color: '#34475F', fontSize: 10 * scale }}>{staffName}（{organName}）</Text></View>
						<View style={styles.type}><Text style={{ color: '#000', fontSize: 10 * scale }}>{visitTypeName}</Text></View>
					</View>
					<View style={styles.cardBottom}>
						{contactorName && mobile ? <View style={styles.flexRow}><Text style={{ fontSize: 12 * scale, color: '#34475F', fontFamily: 'PingFangSC-Semibold' }}>{contactorName || '--'}  {mobile || '--'}</Text></View> : null}
						{visitType == 'VISIT' ? <View style={{ marginTop: 2 * scale }}><Text style={{ color: '#34475F', fontSize: 10 * scale, lineHeight: 24 * scale }}>地址：{detailAddress || '--'}</Text></View> : null}
						<View><Text style={{ color: '#34475F', fontSize: 10 * scale, lineHeight: 20 * scale }}>内容：{content}</Text></View>
					</View>
				</View>
			</TouchableOpacity>
		)
	}

	render() {
		let { modalVisible, showTimeModal, checked, status, listData, refreshIcon } = this.state || {};
		let { ortherData, choice } = this.props;
		return (
			<View style={{ height: '100%' }}>
				<NavigationEvents
					onWillFocus={({ action }) => {
						this.refresh();
					}} />
				<View style={styles.title}>
					<View style={styles.selectTitle}>
						<TouchableOpacity onPress={this._showVisible} style={styles.flexRow}>
							<Text style={{ marginRight: 12 * scale, color: '#34475F', fontSize: 12 * scale, fontFamily: 'PingFangSC-Semibold' }}>
								{this.department || '全部类型'}
							</Text>
							<Image source={require('../../../../../imgs/select.png')} />
						</TouchableOpacity>
						<TouchableOpacity style={styles.flexRow} onPress={this._timeOpen}>
							<Image source={require('../../../../../imgs/time.png')} style={{ tintColor: '#0E7FFD', marginRight: 5 * scale, width: 14 * scale, height: 16 * scale }} />
							<View style={styles.flexRow}>
								<Text style={styles.statusItemText}>{CommonData._format('date1', this.params.beginDate) || ''}</Text>
								<Text style={styles.statusItemText}>-</Text>
								<Text style={styles.statusItemText}>{CommonData._format('date1', this.params.endDate) || ''}</Text>
							</View>
						</TouchableOpacity>
					</View>
				</View>

				{
					modalVisible ?
						<View style={styles.modelOut}>
							<Common styleOut={styles.commonModal}
								itemFn={this._itemFn}
								data={this.headData}
								imgIndex={this.headIndex}
								allClick={this._showVisible}
								type="selectModal"
							/>
						</View> : null
				}
				<View style={styles.middleSelect}>
					<TouchableOpacity style={styles.add}
						onPress={() => { navigationSeevice.navigate('NewMaintenance', { ortherData, choice }) }}>
						<Text style={{ color: '#fff', fontSize: 10 * scale }}>新增维护</Text>
					</TouchableOpacity>
					<TouchableOpacity style={styles.flexRow} onPress={this.changeCheck}>
						{
							checked ?
								<Image source={require('../../../../../imgs/checkbox-checked.png')} style={styles.checkImg} /> :
								<Image source={require('../../../../../imgs/checkbox.png')} style={styles.checkImg} />
						}
						<Text style={{ color: '#0E7FFD', fontSize: 10 * scale }}>仅看自己</Text>
					</TouchableOpacity>
				</View>

				{
					status == 'data' ?
						<View style={{ flex: 1 }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View> : <PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />
				}

				{
					showTimeModal ?
						<RangTime isClear={true}
							isVisible={true}
							markedDates={null}
							startTime={this.params.beginDate}
							endTime={this.params.endDate}
							closeCall={() => { this.setState({ showTimeModal: false }) }}
							resultCall={this._resultCall} /> : null
				}
			</View >
		)
	}
}


const styles = StyleSheet.create({
	flexRow: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	title: {
		backgroundColor: '#FFFFFF',
		borderRadius: 6,
		paddingTop: 22 * scale,
		paddingBottom: 22 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
		zIndex: 100
	},
	selectTitle: {
		paddingLeft: 13 * scale,
		paddingRight: 13 * scale,
		justifyContent: 'space-between',
		flexDirection: 'row',
		alignItems: 'center'
	},
	modelOut: {
		width: '100%',
		height: '100%',
		zIndex: 100,
	},
	commonModal: {
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(0,0,0,0)',
	},
	middleSelect: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		paddingRight: 12 * scale,
		marginTop: 16 * scale,
		marginBottom: 20 * scale
	},
	statusItemText: {
		fontSize: 12 * scale,
		color: '#34475F'
	},
	add: {
		backgroundColor: '#0E7FFD',
		borderRadius: 15.5 * scale,
		paddingTop: 6 * scale,
		paddingBottom: 6 * scale,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale
	},
	checkImg: {
		width: 12 * scale,
		height: 12 * scale,
		marginLeft: 22 * scale,
		marginRight: 10 * scale,
	},
	cardBox: {
		marginBottom: 16 * scale,
		marginLeft: 12 * scale,
		marginRight: 12 * scale,
	},
	card: {
		borderRadius: 6 * scale
	},
	type: {
		backgroundColor: '#E4E8F1',
		borderRadius: 12,
		paddingTop: 4 * scale,
		paddingBottom: 4 * scale,
		paddingLeft: 7 * scale,
		paddingRight: 8 * scale,
	},
	cardTop: {
		paddingTop: 10 * scale,
		paddingBottom: 7 * scale,
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale,
		backgroundColor: '#fff',
		marginBottom: 1 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',

	},
	cardBottom: {
		backgroundColor: '#fff',
		paddingTop: 15 * scale,
		paddingBottom: 13 * scale,
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale,
	}
})